Vue.use(window.vuelidate.default)
var required = window.validators.required

Vue.component('h-flow', {
  props: {
    options: Array,
    optionsUrl: String,
    optValueField: {
      required: true,
      type: String
    },
    optLabelField: {
      required: true,
      type: String
    },
    flows: Array,
    flowsUrl: String,
    valueField: {
      required: true,
      type: String
    },
    labelField: {
      required: true,
      type: String
    },
    readonly: {
      default: false,
      type: Boolean
    },
    color: {
      default: 'primary',
      type: String
    }
  },
  template: `
    <div>
      <q-timeline :color="color">
        <q-timeline-entry
          v-if="!readonly"
          subtitle="创建审批"
        >
          <div>
            <q-btn size="xs" flat :color="color" @click="openAddModal">新增</q-btn>
          </div>
        </q-timeline-entry>
        <q-timeline-entry
          v-for="(flow, index) in cFlows"
          :key="flow.value+index"
          :subtitle="flow.label"
        >
          <div v-if="!readonly">
            <q-btn size="xs" flat :color="color" @click="openInsertModal(flow)">插入</q-btn>
            <q-btn size="xs" flat :color="color" @click="openEditModal(flow, index)">编辑</q-btn>
            <q-btn size="xs" flat color="negative" @click="deleteConfirm(flow, index)">删除</q-btn>
          </div>
        </q-timeline-entry>
      </q-timeline>
      <q-modal no-backdrop-dismiss v-model="addOrEditModal" :content-css="{minWidth: '33vw', minHeight: '350px',borderRadius: '4px'}">
        <q-modal-layout>
          <q-toolbar slot="header" color="white">
            <q-toolbar-title class="text-dark">
              {{ addOrEdit == 0 ? '新增' : (addOrEdit == 1? '编辑' : '插入新增')  }}
            </q-toolbar-title>
            <q-btn flat @click="addOrEditModal = false">
              <q-icon name="close" color="dark"></q-icon>
            </q-btn>
          </q-toolbar>
          <q-card class="q-px-md q-py-sm bg-white no-shadow full-width">
            <q-card-main class="row gutter-x-md gutter-y-sm">
              <q-field 
                :error="$v.form.name.$error"
                error-label="审批人不能为空"
                class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                <q-select
                  float-label="审批人"
                  filter
                  filter-placeholder="输入查询"
                  :options="cOptions"
                  @blur="$v.form.name.$touch"
                  v-model="form.name"></q-select>
              </q-field>
            </q-card-main>
          </q-card>
          <q-toolbar slot="footer" color="white" class="row justify-end">
            <q-btn
              glossy
              size="sm"
              :loading="btnLoading"
              color="primary"
              v-if="addOrEdit == 0"
              @click="saveAddHandler">保存</q-btn>
            <q-btn
              glossy
              size="sm"
              :loading="btnLoading"
              color="primary"
              v-else-if="addOrEdit == 1"
              @click="saveEditHandler">保存</q-btn>
            <q-btn
              glossy
              size="sm"
              :loading="btnLoading"
              color="primary"
              v-else
              @click="saveInsertHandler">保存</q-btn>
            <q-btn
              glossy
              size="sm"
              class="q-ml-sm"
              color="secondary"
              @click="addOrEditModal = false">取消</q-btn>
          </q-toolbar>
        </q-modal-layout>
      </q-modal>
    </div>
  `,
  data: function() {
    return {
      cOptions: this.options?this.options : [],
      cFlows: this.flows?this.flows : [],
      // 内置参数
      addOrEditModal: false,
      btnLoading: false,
      addOrEdit: 0, // 0新增 1编辑 2插入
      editOrInsertFlag: '',
      editIndex: 0,
      form: {
        name: ''
      }
    }
  },
  validations: {
    form: {
      name: { required: required }
    }
  },
  watch: {
    cFlows: {
      handler: function(cFlows) {
        var newFlows = [], that = this
        cFlows.forEach(function(o) {
          var obj = {}
          obj[that.valueField] = o.value
          obj[that.labelField] = o.label
          newFlows.push(obj)
        })
        this.$emit('change', newFlows)
      },
      deep: true
    }
  },
  mounted: function() {
    if (!this.flows) {
      this.getFlowsData()
    }
    if (!this.options) {
      this.getOptionsData()
    }
  },
  methods: {
    getFlowsData: function() {
      var that= this
      this.$api({
        url: this.flowsUrl,
        method: 'post',
        successCallback: function(data) {
          data.forEach(function(d) {
            var _o = {}
            _o.label = d[that.labelField]
            _o.value = d[that.valueField]
            that.cFlows.push(_o)
          })
        },
        errorCallback (err) {
          console.log(err)
        }
      })
    },
    getOptionsData: function() {
      var that = this
      this.$api({
        url: this.optionsUrl,
        method: 'post',
        successCallback: function(data) {
          data.forEach(function(d) {
            var _o = {}
            _o.label = d[that.optLabelField]
            _o.value = d[that.optValueField]
            that.cOptions.push(_o)
          })
        },
        errorCallback (err) {
          console.log(err)
        }
      })
    },
    openAddModal: function() {
      this.addOrEdit = 0
      this.form = {
        name: ''
      }
      this.$v.form.$reset()
      this.addOrEditModal = true
    },
    saveAddHandler: function() {
      var that = this
      this.$v.form.$touch()
      if (!this.$v.form.$error) {
        this.cOptions.forEach(function(o) {
          if (that.form.name == o.value) {
            that.cFlows.push(o)
          }
        })
        this.addOrEditModal = false
      }
    },
    openInsertModal: function(flow) {
      this.addOrEdit = 2
      this.editOrInsertFlag = flow.value
      this.form = {
        name: ''
      }
      this.$v.form.$reset()
      this.addOrEditModal = true
    },
    saveInsertHandler: function() {
      var that = this
      this.$v.form.$touch()
      if (!this.$v.form.$error) {
        var _index 
        this.cFlows.forEach(function(o, i) {
          if (that.editOrInsertFlag == o.value) {
            _index = i
          }
        })
        this.cOptions.forEach(function(o) {
          if (that.form.name == o.value) {
            that.cFlows.splice(_index, 0, o)
          }
        })
        this.addOrEditModal = false
      }
    },
    openEditModal: function(flow, index) {
      var that = this
      this.addOrEdit = 1
      this.cOptions.forEach(function(o) {
        if (o.value == flow.value) {
          that.form.name = o.value
          that.editOrInsertFlag = flow.value // 标记当前被修改的是哪一条数据
          that.editIndex = index  // 若有重复 则通过标记Index来识别是哪一条
        }
      })
      this.addOrEditModal = true
    },
    saveEditHandler: function() {
      var that = this
      this.$v.form.$touch()
      if (!this.$v.form.$error) {
        // 替换掉当前被编辑的审批人  换成新选择的
        var _arr = []
        this.cFlows.forEach(function(o, index) {
          if (that.editOrInsertFlag != o.value) {
            _arr.push(o)
          } else {
            if (that.editIndex != index) {
              _arr.push(o)
            } else {
              that.cOptions.forEach(function(j) {
                if (that.form.name == j.value) {
                  _arr.push(j)
                } 
              })
            }
          }
        })
        this.cFlows = _arr
        this.addOrEditModal = false
      }
    },
    deleteConfirm: function(flow, index) {
      var that = this
      this.$q.dialog({
        title: this.$t('确认')+'？',
        message: this.$t('您确定要在审批流程中移除当前审批人吗')+'？',
        ok: {
          label: this.$t('确认'),
          flat: true
        },
        cancel: {
          label: this.$t('取消'),
          flat: true
        }
      })
      .then(function() {
        var _arr = []
        that.cFlows.forEach(function(o, i) {
          if (flow.value != o.value) {
            _arr.push(o)
          } else {
            if (index != i) {
              _arr.push(o)
            }
          }
        })
        that.cFlows = _arr
      })
      .catch(function() {
        // 选择"Cancel"或作了关闭操作
      })
    }
  }
})